package com.guqj.nio.netty.pstack.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;

import com.guqj.nio.netty.pstack.util.NettyConstant;
import com.guqj.nio.netty.pstack.util.NettyMessageDecoder;
import com.guqj.nio.netty.pstack.util.NettyMessageEncoder;

public class NettyServer {

	public void bind() throws InterruptedException {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4, -8, 0))
									.addLast(new NettyMessageEncoder())
									.addLast(new ReadTimeoutHandler(5))
									.addLast(new LoginAuthRespHandler())
									.addLast(new HeartBeatRespHandler());
						}
					});
			ChannelFuture c = b.bind(NettyConstant.PORT).sync();
			System.out.println("Netty Server start ok : " + NettyConstant.REMOTE_IP + ":" + NettyConstant.PORT);
			c.channel().closeFuture().sync();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		new NettyServer().bind();
	}
}
